var express = require('express');
var router = express.Router();
var User = require('../models/user.js')
require('../util/util.js')
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
  //  登录接口
router.post('/login',function(req,res,next) {
  var param = {
    userName : req.body.userName,
    userPwd : req.body.userPwd
  }

  
  User.findOne(param,function(err,user) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message
      })
    }else {
      if(user) {
        //  设置cookie
        res.cookie('userId',user.userId,{
          path:'/',
          maxAge:1000*60*60
        });
        res.cookie('userName',user.userName,{
          path:'/',
          maxAge:1000*60*60
        });
        //  设置Session
        // req.session.user = user
        res.json({
          status: '0',
          msg: '',
          result: {
            userName:user.userName,
            type:user.type
          }
        })
      }
    }
  })
})

//  注册接口
router.post("/register",function(req,res,next) {
    let userName = req.body.userName
    let userPwd = req.body.userPwd
  User.findOne({userName:userName},function(err,user) {
    if(err) {
      res.json({
        status:'1',
        msg:err.message,
        result:''
      })
    }else{
      if(user) {
        res.json({
          status: '2',
          message:'用户存在，请重新注册',
          result:''
        })
      }else {
        new User({
          userId: Math.floor(Math.random()*10000000+100000000),
          userName:userName,
          userPwd:userPwd
        }).save(function(err) {
          if(err) {
            res.json({
              status:'1',
              msg:err.message,
              result:''
            })
          }else {
            res.json({
              status: '0',
              message:'注册成功',
              result:''
            })
          }
        })
      }
    }
  })
})
  //  登出接口
  router.post("/logout",function(req,res,next) {
    res.cookie("userId","",{
      path:"/",
      maxAge:-1
    })
    res.json({
      status:"0",
      msg:'',
      result:''
    })
  })

  //  校验登录:刷新页面登录信息依然存在
  router.get('/checkLogin',function (req,res,next) {
    if(req.cookies.userId) {
      res.json({
        status:'0',
        msg:'',
        result:req.cookies.userName || ''
      })   
    }else {
      res.json({
        status:'1',
        msg:'未登录',
        result:''
      })
    }
  })

//  查看当前用户购物车数据
router.get("/cartList",function(req,res,next) {
  var userId = req.cookies.userId
  User.findOne({
    userId:userId
  },function(err,user) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message
      })
    }else {
      if(user) {
        res.json({
          status:'0',
          msg:'',
          result:user.cartList
        })
      }
    }
  })
})

//  购物车删除
router.post('/cartDel',function(req,res,next) {
  var userId = req.cookies.userId,
  productId = req.body.productId
  User.update(
    {userId:userId},
    {$pull:
      {'cartList':
        {'productId':productId}
      }
    },function(err) {
      if(err) {
        res.json({
          status:'0',
          msg:err.message,
          result:''
        })
      }else {
        res.json({
          status:'0',
          msg:'',
          result:'suc'
        })
      }
    })
})


//  修改商品数量
router.post('/cartEdit',function(req,res,next) {
  var userId = req.cookies.userId,
      productId = req.body.productId
      productNum = req.body.productNum
      checked = req.body.checked
  User.update(
    {"userId":userId,
    "cartList.productId":productId},
    {"cartList.$.productNum":productNum,
    "cartList.$.checked":checked
    },function(err) {
      if(err) {
        res.json({
          status:'0',
          msg:err.message,
          result:''
        })
      }else {
        res.json({
          status:'0',
          msg:'',
          result:'suc'
        })
      }
    })
})

//  全选并实时修改
router.post('/editCheckAll',function(req,res,next) {
  var userId = req.cookies.userId,
      checkAll = req.body.checkAll?'1':'0'
  User.findOne({userId:userId},function(err,user){
    if(err) {
      res.json({
        status:'0',
        msg:err.message,
        result:''
      })
    }else {
      if(user) {
        user.cartList.forEach((item) => {
          item.checked = checkAll
        })
        user.save(function(err1) {
          if(err1) {
            res.json({
              status:'0',
              msg:err.message,
              result:''
            })
          }else {
            res.json({
              status:'0',
              msg:'',
              result:'suc'
            })
          }
        })
      }
    }
  })
})

//  查询用户地址接口
router.get("/addressList",function(req,res,next) {
  var userId = req.cookies.userId
  User.findOne({userId:userId},function (err,user) {
    if(err) {
      res.json({
        status:'0',
        msg:err.message,
        result:''
      })
    }else {
      res.json({
        status:'0',
        msg:'',
        result:user.addressList
      })
    }
  })
})

//  设置默认地址
router.post("/setDefault",function(req,res,next) {
  var userId = req.cookies.userId
  var addressId = req.body.addressId
  if(!addressId) {
    if(err) {
      res.json({
        status:'0',
        msg:'addressId is null',
        result:''
      })
    }
  }
  User.findOne({userId:userId},function(err,user) {
    if(err) {
      res.json({
        status:'0',
        msg:err.message,
        result:''
      })
    }else {
      var addressList = user.addressList
      addressList.forEach((item) => {
        if(item.addressId == addressId) {
          item.isDefault = true
        }else {
          item.isDefault = false
        }
      })
      user.save(function(err1) {
        if(err1) {
          res.json({
            status:'1',
            msg:err1.message,
            result:''
          })
        }else {
          res.json({
            status: '0',
            msg: '',
            result:addressId
          })
        }
      })
    }
  })

})

//  删除地址
router.post("/delAddress",function(req,res,next) {
  var userId = req.cookies.userId,
  addressId = req.body.addressId
  User.update(
    {userId:userId},
    {$pull:
      {'addressList':
        {'addressId':addressId}
      }
    },function(err) {
      if(err) {
        res.json({
          status:'1',
          msg:err.message,
          result:''
        })
      }else {
        res.json({
          status:'0',
          msg:'',
          result:''
        })
      }
})
})

//  修改地址
router.post("/addaddr",function(req,res,next) {
  var param = {
    addressId: Math.floor(Math.random()*10000+100000),
    userName: req.body.userName,
    streetName: req.body.streetName,
    postCode: req.body.postCode,
    tel: req.body.tel,
    isDefault : false
  }
  var userId = req.cookies. userId
  User.findOne({userId:userId},function(err,user) {
    if(err) {
        res.json({
          status:'1',
          msg:err.message,
          result:''
        })
      }else {
        if(user) {
          var address = param
          user.addressList.push(address)
          user.save(function(err1) {
            if(err1) {
              res.json({
                status:'1',
                msg:err.message,
                result:''
              })
            }else {
              res.json({
                status:'0',
                msg:'',
                result:''
              })
            }
          })
        }
      }
  })
})

//  用户支付
router.post("/payMent",function(req,res,next) {
  var userId = req.cookies.userId,
      orderTotal = req.body.orderTotal,
      addressId = req.body.addressId
  User.findOne({userId:userId},function(err,user) {
      if(err) {
        res.json({
          status:'1',
          msg:err.message,
          result:''
        })
    }else {
      var address = '',
          goodsList= []
      //  获取当前用户的地址信息
      user.addressList.forEach((item) => {
        if(addressId == item.addressId) {
          address = item
        }
      })
        //  获取当前用户购物车的购买商品
        user.cartList.filter((item) => {
          if(item.checked == '1'){
            goodsList.push(item)
          }
        })
        //  生成时间订单号等信息
        var platform = '622'
        var r1 = Math.floor(Math.random()*10)
        var r2 = Math.floor(Math.random()*10)

        var sysDate = new Date().Format('yyyyMMddhhmmss')
        var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss')
        var orderId = platform + r1 +sysDate+r2
      var order = {
        orderId: orderId,
        orderTotal: orderTotal,
        addressInfo: address,
        goodsList: goodsList,
        orderStatus: '1',
        createDate: createDate
      }

      user.orderList.push(order) 
      user.cartList = []
      user.save(function(err1) {
        if(err1) {
          res.json({
            status:'1',
            msg:err1.message,
            result:''
          })
        }else {
          res.json({
            status: '0',
            msg: '',
            result:{
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      })
    }
  })
})

//  根据订单id查询订单信息
router.get('/orderDetail',function(req,res,next) {
  var userId = req.cookies.userId,
      orderId = req.query.orderId
      User.findOne({
        userId:userId},function(err,userInfo) {
          if(err) {
            res.json({
              status:'1',
              msg: err.message,
              result :''
            })
          }else {
            var orderList = userInfo.orderList
            if(orderList.length>0) {
              var orderTotal = 0
              orderList.forEach((item) => {
                if(item.orderId == orderId) {
                  orderTotal = item.orderTotal
                }
              })
              if(orderTotal>0) {
                res.json({
                  status:'0',
                  msg:'',
                  result:{
                    orderId:orderId,
                    orderTotal:orderTotal
                  }
                })
              }else {
                res,json({
                  status:'120002',
                  msg:'无此订单',
                  result:''
                })
              }
              
            }else {
              res,json({
                status:'120001',
                msg:'当前用户未创建订单',
                result:''
              })
            }
          }
        })
      })
//  获取购物车数量
      router.get('/getCartCount',function(req,res,next) {
        if(req.cookies && req.cookies.userId) {
          var userId = req.cookies.userId
          User.findOne({userId:userId},function(err,user) {
            if(err) {
              res.json({
                status:'1',
                msg: err.message,
                result :''
              })
            } else {
              var cartList = user.cartList
              let cartCount = 0
              cartList.map(function (item) {
                cartCount += parseInt(item.productNum)
              })
              res.json({
                status:'0',
                mes:'',
                result:cartCount
              })
            }
          })
        }
      })
module.exports = router
